package club.janna.concurrency.example.notThreadSafe;

import club.janna.concurrency.annotation.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
@ThreadSafe
public class StringExample2 {

    private final static int threadTotal = 5000;
    private final static int threadNum = 200;

    private static StringBuffer stringBuffer = new StringBuffer();

    public static void main(String[] args) {
        final Semaphore semaphore = new Semaphore(threadNum);
        CountDownLatch countDownLatch = new CountDownLatch(threadTotal);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i = 0; i < threadTotal; i ++)
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                update();
                countDownLatch.countDown();
                semaphore.release();
            });
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();
        log.info("size: {}", stringBuffer.length());
    }

    public static void update() {
        stringBuffer.append("1");
    }
}
